package com.zdc.encrypt;

import cn.hutool.core.io.FileUtil;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * @author zdc
 * @description
 * @date 2025/8/14 10:41
 */
public class YamlEncryptorTool {
    public static void jiami() throws Exception {
        String path = YamlEncryptorTool.class.getClassLoader().getResource("").getPath();
        path = path.replaceFirst("/", "");
        String dir = path.replace("target/classes/", "src/main/resources/");
        System.err.println("请输入加密密码(***请牢记***谨慎操作***)，密码丢失将无法恢复/修改配置文件");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String password = br.readLine();
        MultiYamlEncryptor encryptor = new MultiYamlEncryptor(password, dir);
        // 加密所有YAML文件
        Map<String, byte[]> encryptedFiles = encryptor.encryptAllYamls();
        // 写入加密文件
        if (encryptedFiles.keySet().size() <= 0) {
            System.out.println("未发现有效配置文件，请确认！");
            System.exit(1);
        }
        System.out.println("保存目录：" + dir);
        for (Map.Entry<String, byte[]> entry : encryptedFiles.entrySet()) {
            try (FileOutputStream out = new FileOutputStream(dir + entry.getKey())) {
                out.write(entry.getValue());
            }
            System.out.println("已加密保存: " + entry.getKey());
            FileUtil.del(dir + entry.getKey().replace(".yml.gz", ".yml"));
        }
    }

    public static void jiemi() throws Exception {
        String path = YamlEncryptorTool.class.getClassLoader().getResource("").getPath();
        path = path.replaceFirst("/", "");
        String dir = path.replace("target/classes/", "src/main/resources/");
        System.out.println("请输入解密密码");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String password = br.readLine();
        MultiYamlEncryptor encryptor = new MultiYamlEncryptor(password, dir);
        // 解密所有YAML文件
        Map<String, String> decryptedFiles = encryptor.decryptAllYamls();
        if (decryptedFiles.keySet().size() <= 0) {
            System.out.println("未发现有效加密配置文件，请确认！");
            System.exit(1);
        }
        // 写入解密文件
        System.out.println("保存目录：" + dir);
        for (Map.Entry<String, String> entry : decryptedFiles.entrySet()) {
            try (FileOutputStream out = new FileOutputStream(dir + entry.getKey())) {
                out.write(entry.getValue().getBytes());
            }
            System.out.println("已解密恢复: " + entry.getKey());
        }
    }
}
